# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=flac
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.5.0
pkgrel=1
pkgdesc="Free Lossless Audio Codec (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://xiph.org/flac/"
msys2_references=(
  "cpe: cpe:/a:flac_project:flac"
)
license=('custom:Xiph' 'LGPL' 'GPL' 'FDL')
depends=("${MINGW_PACKAGE_PREFIX}-libogg"
         "${MINGW_PACKAGE_PREFIX}-gettext-runtime"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread"
         "${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-gettext-tools"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/xiph/flac/releases/download/${pkgver}/flac-${pkgver}.tar.xz")
sha256sums=('f2c1c76592a82ffff8413ba3c4a1299b6c7ab06c734dee03fd88630485c2b920')

build() {
  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  mkdir -p "${srcdir}/build-${MSYSTEM}-static" && cd "${srcdir}/build-${MSYSTEM}-static"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -Wno-dev \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DBUILD_DOCS=OFF \
    -DBUILD_SHARED_LIBS=OFF \
    -DBUILD_TESTING=OFF \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./

  mkdir -p "${srcdir}/build-${MSYSTEM}-shared" && cd "${srcdir}/build-${MSYSTEM}-shared"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -Wno-dev \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DBUILD_DOCS=OFF \
    -DBUILD_SHARED_LIBS=ON \
    -DBUILD_TESTING=OFF \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

check() {
  cd "${srcdir}/build-${MSYSTEM}-static"
  ${MINGW_PREFIX}/bin/cmake ../${_realname}-${pkgver} -DBUILD_TESTING=ON
  ${MINGW_PREFIX}/bin/cmake --build .
  ${MINGW_PREFIX}/bin/ctest.exe ./ || true

  cd "${srcdir}/build-${MSYSTEM}-shared"
  ${MINGW_PREFIX}/bin/cmake ../${_realname}-${pkgver} -DBUILD_TESTING=ON
  ${MINGW_PREFIX}/bin/cmake --build .
  PATH=$PWD/src/libFLAC:$PWD/src/libFLAC++:$PATH ${MINGW_PREFIX}/bin/ctest.exe ./ || true
}

package() {
  cd "${srcdir}/build-${MSYSTEM}-static"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install ./

  cd "${srcdir}/build-${MSYSTEM}-shared"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install ./

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/COPYING.Xiph" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/COPYING.Xiph"
}
